using System.Text;

namespace welog.core;

public class WelogHandleBase
{
    /// <summary>
    /// 更新每一行记录
    /// </summary>
    /// <param name="line">行内容</param>
    /// <param name="lastTime">行日期</param>
    /// <returns></returns>
    protected string UpdateData(string line,string lastTime)
    {
        var items = line.Split("|");
        if (items.Length == 14)
        {
            if(string.IsNullOrWhiteSpace(items[11]))
            {
                items[11] = lastTime;
            }
            if(string.IsNullOrWhiteSpace(items[12]))
            {
                items[12] = lastTime;
            }
            return $"{string.Join('|',items)}";
        }
        else
        {
            return line;
        }
    }

    protected void MdToCsv(string fileName, string mdContent)
    {
        try
        {
            var reportDir = "report";

            if (!Directory.Exists(reportDir))
            {
                Directory.CreateDirectory(reportDir);
            }
            // 将Markdown内容转换为CSV格式
            string csvContent = MdToCsv(mdContent);
            // 写入到文件
            File.WriteAllText(Path.Combine(reportDir,fileName), csvContent);
            Console.WriteLine("CSV文件已成功生成！");
        }
        catch (Exception e)
        {
            Console.WriteLine(e);
            throw;
        }
        
    }
    
    private string MdToCsv(string mdContent)
    {
        // 分割成行
        var lines = mdContent.Split(new[] {"\n" }, StringSplitOptions.None);
        var csvBuilder = new System.Text.StringBuilder();

        foreach (var line in lines)
        {
            // 去除首尾的'|'字符并分割
            var items= RemoveFirstAndLastOccurrence(line, '|');
            items = items.Replace(',', ';');
            items = items.Replace('|', ',');
            // 添加到CSV builder中
            csvBuilder.AppendLine(items);
        }

        return csvBuilder.ToString();
    }
    
    private string RemoveFirstAndLastOccurrence(string source, char value)
    {
        int firstIndex = source.IndexOf(value);
        if (firstIndex == -1) return source; // 如果没有找到字符，则返回原字符串
        
        int lastIndex = source.LastIndexOf(value);
        if (lastIndex == -1 || lastIndex == firstIndex) return source; // 确保找到了最后一个不同的位置

        // 移除第一个和最后一个位置的字符
        string result = source.Remove(lastIndex, 1).Remove(firstIndex, 1);
        return result;
    }
}